import pandas as pd
import plotly.graph_objects as go
from nicegui import ui

# 初始化数据
df = pd.DataFrame(columns=['x', 'y', 'z'])

# 创建三维散点图
def create_3d_plot():
    fig = go.Figure(data=[go.Scatter3d(
        x=df['x'],
        y=df['y'],
        z=df['z'],
        mode='markers',
        marker=dict(
            size=8,
            color='blue',
            opacity=0.8
        )
    )])
    fig.update_layout(
        scene=dict(
            xaxis_title='X轴',
            yaxis_title='Y轴',
            zaxis_title='Z轴',
            xaxis=dict(
                showgrid=True,
                zeroline=True,
                showline=True,
                showticklabels=True,
                showspikes=True,
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            yaxis=dict(
                showgrid=True,
                zeroline=True,
                showline=True,
                showticklabels=True,
                showspikes=True,
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            ),
            zaxis=dict(
                showgrid=True,
                zeroline=True,
                showline=True,
                showticklabels=True,
                showspikes=True,
                showbackground=True,
                backgroundcolor='rgb(230, 230,230)'
            )
        ),
        margin=dict(l=0, r=0, b=0, t=0)
    )
    return fig

# 创建UI界面
with ui.row():
    x_input = ui.number('X坐标').classes('w-32')
    y_input = ui.number('Y坐标').classes('w-32')
    z_input = ui.number('Z坐标').classes('w-32')

plot = ui.plotly(create_3d_plot()).classes('w-full h-[500px]')

# 添加点的函数
def add_point():
    try:
        x = float(x_input.value)
        y = float(y_input.value)
        z = float(z_input.value)
        global df
        df = pd.concat([df, pd.DataFrame({'x': [x], 'y': [y], 'z': [z]})], ignore_index=True)
        plot.update_figure(create_3d_plot())
        ui.notify('点已添加')
    except ValueError:
        ui.notify('请输入有效的数值！', type='warning')

# 删除最后一个点的函数
def delete_last_point():
    global df
    if not df.empty:
        df = df.iloc[:-1]
        plot.update_figure(create_3d_plot())
        ui.notify('最后一个点已删除')
    else:
        ui.notify('没有点可以删除', type='warning')

with ui.row():
    ui.button('添加点', on_click=add_point)
    ui.button('删除最后一个点', on_click=delete_last_point)

ui.run(port=8000)